// const service = require('/utils/service.js');
const tool = require('./tool.js');
// const order = require('/utils/order.js');
// const utils = require('/utils/util.js');
const bleTool = require('./bleTool.js');
const order = require('./order.js');
const operateService = "0000FFE0-0000-1000-8000-00805F9B34FB";
const notifyCharacteristics = "0000FFE4-0000-1000-8000-00805F9B34FB"; 
const writeCharacteristics = "0000FFE9-0000-1000-8000-00805F9B34FB"; 

var BLEData = {
  BLEOpen: false,
  devices: Array(),
  deviceNames:Array(),
  connectedDevice: null,//当前连接的设备
  willConnectDevice: null,//将要连接的设备
  order: "",
  BLEInfo: "",
  latestDataStr:"",
  dataArray: Array()
}

function getBLEData() {
  return BLEData;
}

function setBLEData(bleData) {
  BLEData = bleData;
}

/**
 * 开启蓝牙适配器
 */ 
function openBluetoothAdapter() {
  let that = this;
  var currentPages = getCurrentPages();
  var currentPage = currentPages[currentPages.length - 1];
  wx.getSetting({
    success(res) {
      if (!res.authSetting['scope.bluetooth']) {
        wx.authorize({
          scope: 'scope.bluetooth',
          success () {
            console.log("我是有权限的");
            wx.openBluetoothAdapter({
              success: (res) => {
                console.log('openBluetoothAdapter success', res);
                BLEData.BLEOpen = true;
                // if(currentPage.BLEOpenStatus){
                //   currentPage.BLEOpenStatus();
                // }
              },
              fail: (res) => {
                console.log(res);
                if (res.errCode === 10001) {
                  BLEData.BLEOpen = false;
                //   if(currentPage.BLEOpenStatus){
                //     currentPage.BLEOpenStatus();
                //   }
                  wx.onBluetoothAdapterStateChange(function (res) {
                    console.log('onBluetoothAdapterStateChange', res)
                    if (res.available) {
                      BLEData.BLEOpen = true;
                    }else {
                      BLEData.BLEOpen = false;
                      wx.showToast({
                        title: '蓝牙打开失败，请检查',
                        icon: 'none'
                      })
                      if(currentPage.writeError){
                        currentPage.writeError();
                      }
                    }
                  })
                }else {
                //   if(currentPage.BLEOpenStatus){
                //     currentPage.BLEOpenStatus();
                //   }
                }
              }
            })
          },
          fail(){
            console.log("没有授权");
            wx.showModal({
              title: "提示",
              content: "请授权CF尾翼使用蓝牙",
              showCancel: true,
              cancelColor: "#666666",
              confirmText: "去授权",
              confirmColor: "#45C99A",
              success: function(res){
                if(res.confirm){
                  wx.openSetting({
                    success (res) {
                      console.log(res);
                      if(res.authSetting["scope.bluetooth"] == true){
                        BLEData.BLEOpen = true;
                        wx.openBluetoothAdapter({
                          success: (res) => {
                            console.log('openBluetoothAdapter success', res);
                            BLEData.BLEOpen = true;
                            // if(currentPage.BLEOpenStatus){
                            //   currentPage.BLEOpenStatus();
                            // }
                          },
                          fail: (res) => {
                            console.log(res);
                            if (res.errCode === 10001) {
                              BLEData.BLEOpen = false;
                            //   if(currentPage.BLEOpenStatus){
                            //     currentPage.BLEOpenStatus();
                            //   }
                              wx.onBluetoothAdapterStateChange(function (res) {
                                console.log('onBluetoothAdapterStateChange fail', res)
                                if (res.available) {
                                  BLEData.BLEOpen = true;
                                }else {
                                  BLEData.BLEOpen = false;
                                  wx.showToast({
                                    title: '蓝牙打开失败，请检查',
                                    icon: 'none'
                                  })
                                  if(currentPage.writeError){
                                    currentPage.writeError();
                                  }
                                }
                                // if(currentPage.BLEOpenStatus){
                                //   currentPage.BLEOpenStatus();
                                // }
                              })
                            }else {
                            //   if(currentPage.BLEOpenStatus){
                            //     currentPage.BLEOpenStatus();
                            //   }
                            }
                          }
                        });
                      }else {
                        wx.showToast({
                          title: '您需要授权蓝牙才能操作设备',
                          icon: 'none'
                        })
                      }
                    }
                  })
                }
              },
            })
          }
        })
      }else {
        console.log("有权限");
        wx.openBluetoothAdapter({
          success: (res) => {
            console.log('openBluetoothAdapter success', res);
            BLEData.BLEOpen = true;
            // if(currentPage.BLEOpenStatus){
            //   currentPage.BLEOpenStatus();
            // }
          },
          fail: (res) => {
            console.log(res);
            if (res.errCode === 10001) {
              BLEData.BLEOpen = false;
              wx.showToast({
                title: '蓝牙打开失败，请检查',
                icon: 'none'
              })
            //   if(currentPage.BLEOpenStatus){
            //     currentPage.BLEOpenStatus();
            //   }
              wx.onBluetoothAdapterStateChange(function (res) {
                console.log('onBluetoothAdapterStateChange fail', res)
                if (res.available) {
                  BLEData.BLEOpen = true;
                }else {
                  BLEData.BLEOpen = false;
                  wx.showToast({
                    title: '蓝牙打开失败，请检查',
                    icon: 'none'
                  })
                  if(currentPage.writeError){
                    currentPage.writeError();
                  }
                }
                // if(currentPage.BLEOpenStatus){
                //   currentPage.BLEOpenStatus();
                // }
              })
            }else {
            //   if(currentPage.BLEOpenStatus){
            //     currentPage.BLEOpenStatus();
            //   }
                BLEData.BLEOpen = false;
                wx.showToast({
                title: '蓝牙打开失败，请检查',
                icon: 'none'
                })
            }
          }
        })
      }
    }
  })
}

/**
 * 监听蓝牙状态
 */
function getBluetoothAdapterState() {
  let that = this;
  wx.getBluetoothAdapterState({
    success: (res) => {
      console.log('getBluetoothAdapterState', res)
      if (res.available) {
        BLEData.BLEOpen = true;
      }else {//蓝牙未开启
        BLEData.BLEOpen = false;
        that.stopBluetoothDevicesDiscovery();
      }
    //   if(currentPage.BLEOpenStatus){
    //     if(res.available && res.discovering == false){
    //         currentPage.BLEOpenStatus();
    //     }
    //   }
    }
  })
}

/**
 * 开始扫描蓝牙
 */
function startBluetoothDevicesDiscovery() {
  let that = this;
  console.log("开始执行");
  // that.stopBluetoothDevicesDiscovery();
  wx.startBluetoothDevicesDiscovery({
    allowDuplicatesKey: false,
    success: (res) => {
      console.log('startBluetoothDevicesDiscovery success', res)
      that.onBluetoothDeviceFound()
    },
    fail:(res)=>{
        console.log("搜索失败");
        console.log(res);
    }
  })
}

/**
 * 停止蓝牙扫描
 */
function stopBluetoothDevicesDiscovery() {
  let that = this;
  console.log("取消搜索");
  wx.stopBluetoothDevicesDiscovery()
}

/**
 * 发现蓝牙设备
 */
function onBluetoothDeviceFound() {
  /**
  * 发现蓝牙设备
  */
  wx.onBluetoothDeviceFound((res) => {
    let that = this;
    console.log("我在搜索设备");
    console.log(res);
    res.devices.forEach(device => {
        if (!device.name && !device.localName) {
            return
        }
        if(device.localName != undefined){
            if (device.localName.search("HZHL") != -1) {//是尾翼设备
                console.log("我是尾翼设备呀") 
                if(BLEData.deviceNames.indexOf(device.localName) == -1){
                    BLEData.deviceNames.push(device.localName);
                    BLEData.devices.push(device);
                }
            }
        }
        if(BLEData.devices.length != 0){
            console.log("扫描到了设备");
            var currentPages = getCurrentPages();
            var currentPage = currentPages[currentPages.length - 1];
            if(currentPage.onSearchDevice){
            currentPage.onSearchDevice();
            }
        }

    })

    // wx.getBluetoothDevices({
    //   success: function(resDevice) {
    //     console.log(resDevice)
    //     var wyList = [];
    //     resDevice.devices.forEach(device => {
    //       if(device.localName != undefined){
    //         if (device.localName.search("HZHL") != -1) {//是尾翼设备
    //           if (wyList.indexOf(device.localName) == -1) {
    //             wyList.push(device);
    //           }
    //         }
    //       }
    //     })
    //     if(wyList.length != 0){
    //       console.log("扫描到了设备");
    //       //得到蓝牙设备回调
    //       BLEData.devices = wyList;
    //       var currentPages = getCurrentPages();
    //       var currentPage = currentPages[currentPages.length - 1];
    //       if(currentPage.onSearchDevice){
    //         currentPage.onSearchDevice();
    //       }
    //     }
    //   }
    // })
  })
}

/**
 * 连接蓝牙
 */
function createBLEConnection(device) {
    console.log("开始连接蓝牙");
    console.log(device);
    console.log(device.deviceId);
    console.log(device.name);
    let that = this;
    if(BLEData.connectedDevice != null){
        if (device.deviceId != BLEData.connectedDevice.deviceId) {
            if (BLEData.connectedDevice.deviceId != undefined){
                that.closeBLEConnection(device);//关闭前一个，连接这个
            }
        }else {
            //当前连接的设备没变
            console.log("当前连接的设备没变");
            var currentPages = getCurrentPages();
            var currentPage = currentPages[currentPages.length - 1];
            if (currentPage.haveConnected) {
            currentPage.haveConnected();
            }
            return;
        }
    }else {
        that.connectBle(device);//连接蓝牙
    }


//   wx.getConnectedBluetoothDevices({
//     success: function (res) {
//       if(res.devices.length != 0){
//         var connectedDevice = res.devices[0];
//         if (connectedDevice.deviceId != BLEData.connectedDevice.deviceId) {
//           console.log("连接的时候出现问题");
//           if (BLEData.connectedDevice.deviceId != undefined){
//             that.closeBLEConnection(device);
//           }
//         } else {
//           //当前连接的设备没变
//           console.log("当前连接的设备没变");
//           var currentPages = getCurrentPages();
//           var currentPage = currentPages[currentPages.length - 1];
//           if (currentPage.haveConnected) {
//             currentPage.haveConnected();
//           }
//           return;
//         }
//       }else {
//         console.log("我在开始准备连接蓝牙");
//         console.log(device.deviceId);
//         console.log(device.name);
//         that.connectBle(device);//连接蓝牙
//       }
//     }
//   })
// console.log("我在开始准备连接蓝牙");
// console.log(device.deviceId);
// console.log(device.name);
// that.connectBle(device);//连接蓝牙
}

//连接蓝牙
function connectBle (device){
  let that = this;
//   that.stopBluetoothDevicesDiscovery();
//   setTimeout(function () {
    /**
    * 连接蓝牙
    */
    wx.createBLEConnection({
      deviceId: device.deviceId,
      success: (res) => {
        BLEData.willConnectDevice = null;
        BLEData.connectedDevice = device;
        that.getBLEDeviceServices(device);
        // that.stopBluetoothDevicesDiscovery();
      },
      fail: (res) => {
        console.log("连接失败");
        //进行页面操作
        var currentPages = getCurrentPages();
        var currentPage = currentPages[currentPages.length - 1];
        if (currentPage.connectFail) {
          currentPage.connectFail();
        }
        wx.showToast({
          title: '连接失败',
          icon: 'none'
        })
      }
    })
    // that.stopBluetoothDevicesDiscovery()
//   }, 500)
}

/**
 * 断开蓝牙连接
 */
function closeBLEConnection(willConnectDevice) {
  let that = this;
  console.log("断开蓝牙连接");
  wx.closeBLEConnection({
    deviceId: BLEData.connectedDevice.deviceId,
    success: function(res){
      console.log("断开蓝牙成功");
      //进行页面操作
      BLEData.connectedDevice = null;
      if(willConnectDevice != null){
        that.connectBle(willConnectDevice);
      }
      var currentPages = getCurrentPages();
      var currentPage = currentPages[currentPages.length - 1];
      if (currentPage.disconnect) {
        currentPage.disconnect();
      }
    },
    fail: function(res){
      console.log("蓝牙断开失败");
    //   bleData.BLEOpen = false;
      console.log(res);
    }
  })

}

/**
 * 获取设备服务
 */
function getBLEDeviceServices(device) {
  let that = this;
  /**
  * 获取设备服务
  */
  wx.getBLEDeviceServices({
    deviceId: device.deviceId,
    success: (res) => {
      console.log("扫描到了设备的服务"); 
      console.log(res.services);
      for (let i = 0; i < res.services.length; i++) {
        if (res.services[i].isPrimary) {
          if (res.services[i].uuid == operateService) {
            that.getBLEDeviceCharacteristics(device, res.services[i].uuid)
            return
          }
        }
      }
    }
  })
}

/**
 * 获取蓝牙特征值
 */
function getBLEDeviceCharacteristics(device, serviceId) {
  let that = this;
  /**
  * 获取蓝牙特征值
  */
  wx.getBLEDeviceCharacteristics({
    deviceId:device.deviceId,
    serviceId,
    success: (res) => {
      console.log('getBLEDeviceCharacteristics success', res.characteristics);
      that._serviceId = serviceId
      for (let i = 0; i < res.characteristics.length; i++) {
        let item = res.characteristics[i]
        if (item.uuid == notifyCharacteristics) {
          if (item.properties.notify || item.properties.indicate) {
            console.log("监听");
            wx.notifyBLECharacteristicValueChange({
              deviceId:device.deviceId,
              serviceId:serviceId,
              type: "notification",
              characteristicId: item.uuid,
              state: true,
              success: function (res) {
                console.log("开启监听");
                BLEData.connectedDevice = device;
                // var order = "info:?\r\n";
                // that.writeBLECharacteristicValue(order);
                //判断下发命令
                var currentPages = getCurrentPages();
                var currentPage = currentPages[currentPages.length - 1];
                if(currentPage.haveConnected){
                  currentPage.haveConnected();
                }
                // if(currentPage){
                //   if (currentPage.route == 'pages/bind/bind' || currentPage.route == 'pages/alarmList/alarmList' || currentPage.route == 'pages/debug/debug') {//如果是这两个界面 
                //     setTimeout(function () {
                //       currentPage.bleConnect();//设备连接回调
                //     }, 500);
                //   }
                // }

              },
              fail: function(res){
                console.log("监听失败");
              }
            })
          }
        }
      }
    },
    fail(res) {
      console.error('getBLEDeviceCharacteristics', res)
    }
  })

  /**
   * 监听蓝牙数据改变
   */
  // 操作之前先监听，保证第一时间获取数据
  wx.onBLECharacteristicValueChange((characteristic) => {
    let that = this;
    var currentPages = getCurrentPages();
    var currentPage = currentPages[currentPages.length - 1];
    var data = tool.arrBufToString(characteristic.value);
    console.log("获取到的数据" + data);
    if(data.indexOf("cmd:ok") != -1){
      wx.showToast({
        title: '指令发送成功',
        icon: "success"
      });
    }else if (data.indexOf("cmd:err") != -1){
      wx.showToast({
        title: '指令发送失败',
        icon: "error"
      });
    }else {
      if (data.indexOf("info:") !== -1) {
        console.log("字符串包含子字符串");
        BLEData.BLEInfo = data;
      }else {
        if (data.indexOf("dbg") !== -1){
          const now = new Date();
          var time = that.formatTime(now);
          BLEData.dataArray.push({
            "data": data,
            "time": time
          });
          // console.log(BLEData.dataArray);
        }
        if(currentPage.getDataBlock){
            BLEData.latestDataStr = data;
            currentPage.getDataBlock(data);
        }
      } 
    }
  })
}

/**
 * 写数据到蓝牙
 */
function writeBLECharacteristicValue(order) {//labelsComplete数据量和我的到的总量不同
  var that = this;
  if(order.length == 0){
    return;
  }
  var currentPages = getCurrentPages();
  var currentPage = currentPages[currentPages.length - 1];
  BLEData.order = order;
  console.log(BLEData.order);
  var buffer;
  buffer = tool.stringToArrayBuffer(order);
  wx.writeBLECharacteristicValue({
    deviceId: BLEData.connectedDevice.deviceId,
    serviceId: that._serviceId,
    characteristicId: writeCharacteristics,
    value: buffer,
    success(res){
      console.log("数据写入成功" + order);
      //"cmd:ok"
      // that.globalData.order = order;
    },
    fail(res){
      console.log("数据写入失败 " )
      console.log(res)
      if (res.errCode == 10006 || res.errCode == 10001){
        that.closeBLEConnection();
        BLEData.connectedDevice = null;
        var currentPages = getCurrentPages();
        var currentPage = currentPages[currentPages.length - 1];
        if(currentPage.writeError){
          currentPage.writeError();
        }
      }
      BLEData.order = "";
    }
  })
}

function closeBluetoothAdapter() {
  let that = this;
  wx.closeBluetoothAdapter()
  // that.globalData.isBleOpen = false;
  // that._discoveryStarted = false;
}  

function formatTime(date) {
  var that = this;
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(that.formatNumber).join('/') + ' ' + [hour, minute, second].map(that.formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}


module.exports = {
  getBLEData: getBLEData,
  setBLEData: setBLEData,
  openBluetoothAdapter: openBluetoothAdapter,
  getBluetoothAdapterState: getBluetoothAdapterState,
  startBluetoothDevicesDiscovery: startBluetoothDevicesDiscovery,
  stopBluetoothDevicesDiscovery: stopBluetoothDevicesDiscovery,
  onBluetoothDeviceFound: onBluetoothDeviceFound,
  createBLEConnection: createBLEConnection,
  connectBle: connectBle,
  closeBLEConnection: closeBLEConnection,
  getBLEDeviceServices: getBLEDeviceServices,
  getBLEDeviceCharacteristics: getBLEDeviceCharacteristics,
  writeBLECharacteristicValue: writeBLECharacteristicValue,
  formatTime: formatTime,
  formatNumber: formatNumber
}